package com.ay.weixin.templatereply.domain;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.commons.httpclient.HttpException;
import org.lizar.config.keys.Keys;
import org.lizar.exception.LifecycleException;
import org.lizar.ioc.Container;
import org.lizar.ioc.Lifecycle;
import org.lizar.ioc.module.Module;
import org.lizar.json.JObject;
import org.lizar.log.Log;
import org.lizar.util.MyMath;
import org.lizar.util.https.Https;

import com.ay.weixin.autoreply.domain.AccessTokenModule;

public class TemplateReply extends Module implements Lifecycle{
	
	private static AccessTokenModule access_token_model;

	private static Log log=org.lizar.log.Logger.newInstance(TemplateReply.class);

	private static ConcurrentLinkedQueue<ReplyMsg> queue=new java.util.concurrent.ConcurrentLinkedQueue<ReplyMsg>();
	
	public static void asyReply(ReplyMsg msg){
		queue.add(msg);
	}
	
	@Override
	public void init_property() throws Exception {
		access_token_model=Container.get(AccessTokenModule.class);
		
		
	}
	
	public static void syncReply(ReplyMsg msg){
		reply(msg.getWxproject_id(),msg.getOpenid(),msg.getTemplate_id(),msg.getTopcolor(),msg.getMsg_link(),msg.getData_params());
	}
	
	public static void syncReply(long wxproject_id,String openid,String template_id,JObject data_params){
		reply(wxproject_id,openid,template_id,ReplyMsg.BLUE,"",data_params);
	}
	
	public static void syncReply(long wxproject_id,String openid,String template_id,String msg_link,JObject data_params){
		reply(wxproject_id,openid,template_id,ReplyMsg.BLUE,msg_link,data_params);
	}
	
	public static void syncReply(long wxproject_id,String openid,String template_id,String topcolor,String msg_link,JObject data_params){
		reply(wxproject_id,openid,template_id,topcolor,msg_link,data_params);
	}
	
	private static void reply(long wxproject_id,String openid,String template_id,String topcolor,String msg_link,JObject data_params){
		JObject body=new JObject();
		body.put("touser", openid);
		body.put("template_id", template_id);
		body.put("url", msg_link);
		body.put("topcolor", topcolor);
		body.put("data", data_params);
		try {
			log.info("msg_body:"+body.toString());
			String result=Https.PostMethod(String.format(Keys.getStr("template_reply.post_reply_url"), access_token_model.getAccessToken(wxproject_id)), 
					body.toString());
			log.info("template reply result:"+result);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * :{ "touser" : "" , "template_id" : "" , "url" : "http://www.baidu.com" , "topcolor" : "#FF0000" , "data" : { "first" : { "value" : "璐︽埛娉ㄥ唽鎴愬姛" , "color" : "#BBBBBB"} , "name" : { "value" : "鎴存枃褰 , "color" : "#FF0000"} , "time" : { "value" : "2014-10-18 20:20:36" , "color" : "#FF0000"} , "remark" : { "value" : "鐘舵€侊細NOT_VERIFY锛岃绛夊緟鎴戜滑鐨勫伐浣滀汉鍛樹负鎮ㄥ鏍}}}
	 * */
	public static void main(String[] args){
		testSendMessage();
	}
	

	
	private static void testSendMessage(){
		JObject params=new JObject();
		JObject first=new JObject();
		first.put("value", "11");
		first.put("color", ReplyMsg.BLUE);
		params.put("first", first);
		
		JObject name=new JObject();
		name.put("value", "22");
		name.put("color", ReplyMsg.BLUE);
		params.put("name", name);
		
		JObject time=new JObject();
		time.put("value", "33");
		time.put("color", ReplyMsg.BLUE);
		params.put("time", time);
		
		
		JObject remark=new JObject();
		remark.put("value","44");
		remark.put("color", ReplyMsg.LIGHT_BLACK);
		params.put("remark", remark);
		
		
		JObject body=new JObject();
		System.out.println(MyMath.encryptionWithMD5("oFONCtwHGYCMJIU2dfJcqEtZB3ec"));
		body.put("touser", "oFONCtwHGYCMJIU2dfJcqEtZB3ec");
		body.put("template_id", "-V5uk5p0dlkufRsVFcaWiRj-N4yhb3h23C28kkWbjt0");
		//body.put("url", "");
		//body.put("topcolor", ReplyMsg.BLUE);
		body.put("data", params);
		try {
			log.info("msg_body:"+body.toString());
			String result=Https.PostMethod(String.format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s", 
					"64n0fFvpkf9OF9cyRCj39Y6G-GHCMPvq2pc2ueJAKUkHx-s6tbVl7BwGpIS28BruxdWp_DzJ3dcMsNYFGKQt9A-iURmIill4U2tsvrDWQLg"), 
					body.toString());
			log.info("template reply result:"+result);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	@Override
	public void init_component() throws Exception {
		Thread insert=new Thread(new Runnable() {
			@Override
			public void run() {
				while(!need_to_stop){
					ReplyMsg msg=queue.poll();
					while(msg!=null){
							log.info("begin to send template reply.");
							try {
								reply(msg.getWxproject_id(),msg.getOpenid(),msg.getTemplate_id(),msg.getTopcolor(),msg.getMsg_link(),msg.getData_params());
							} catch (Exception e) {
								e.printStackTrace();
							}
							msg=queue.poll();
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		insert.start();
	}
	
	private boolean need_to_stop=false;

	@Override
	public void born() throws LifecycleException, Exception {
		System.out.println("born of template reply");
	}

	@Override
	public void die() throws LifecycleException {
		System.out.println("end of template reply");
		need_to_stop=true;
	}
	
}
